package com.cszy.yydqbfq.ui.fragment

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.hbcysd.qybfq.databinding.FragmentSingerListBinding
import com.cszy.yydqbfq.adapter.GeDanListAdapter
import com.cszy.yydqbfq.adapter.IndexListAdapter
import com.cszy.yydqbfq.base.BaseVMFragment
import com.cszy.yydqbfq.bean.AudioItemBean
import com.cszy.yydqbfq.bean.Song
import com.cszy.yydqbfq.common.PlaylistRepository
import com.cszy.yydqbfq.dialog.BottomCreateSongPop
import com.cszy.yydqbfq.dialog.BottomPopupWithGeDanRecycler
import com.cszy.yydqbfq.ext.launch
import com.cszy.yydqbfq.ext.toast
import com.cszy.yydqbfq.listener.OnCreateSongListener
import com.cszy.yydqbfq.ui.activity.CreatSongListActivity
import com.cszy.yydqbfq.ui.activity.GeDanListActivity
import com.cszy.yydqbfq.ui.activity.MusicListActivity
import com.cszy.yydqbfq.ui.activity.PlayDetailActivity
import com.cszy.yydqbfq.utils.SpUtils
import com.cszy.yydqbfq.viewmodel.SongListViewModel
import com.hbcysd.qybfq.R
import com.hjq.permissions.XXPermissions
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.hnyyac.ad.mds.utils.BaseAdConstants
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.litepal.LitePal


class SingerListFragment : BaseVMFragment<SongListViewModel, FragmentSingerListBinding>(),IAdViewListener,OnCreateSongListener {

    private lateinit var madapter: GeDanListAdapter
    private var selectMode:Boolean=false    //是否显示选择删除歌单
    private var newGromoreFeedAd : NewGroMoreFeedAdManager? =null
    var type_proces: String? = null //功能入口类型
    var app_process: String? = "0" //整个应用流程
    private var listAdapter: IndexListAdapter? = null
    // 方案2：修正 lazy 初始化
    private val bottomCreateSongPop by lazy {
        BottomCreateSongPop(requireActivity(),this)
    }




    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.init(requireActivity())
        app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
        mBinding.layoutCommonTitle.tvHomeTitle.text = "歌单"
    }

    override fun initData() {
        newGromoreFeedAd = NewGroMoreFeedAdManager(requireActivity(), BaseAdConstants.FEEDAD_Id, mBinding?.frameLayoutBanner,22)
        newGromoreFeedAd?.loadAd()
        madapter= GeDanListAdapter()
        mBinding.recyGedan.layoutManager= LinearLayoutManager(requireContext())
        mBinding.recyGedan.adapter=madapter


        initBlackList()
    }

    private fun initBlackList() {
        if (app_process?.equals("0") == true){
            mBinding.recyLocationList.visibility= View.VISIBLE
            mBinding.tvLocationTitle.visibility = View.VISIBLE
            listAdapter= IndexListAdapter()
            mBinding.recyLocationList.layoutManager= LinearLayoutManager(requireActivity())
            mBinding.recyLocationList.adapter=listAdapter

            listAdapter?.setOnItemClickListener { adapter, view, position ->
                // 传递整个列表和当前点击位置
                var songList=mViewModel.convertToSongInfoList(adapter.items)
                val intent = Intent(requireActivity(), PlayDetailActivity::class.java).apply {
                    putParcelableArrayListExtra("MUSIC_LIST", ArrayList(songList))
                    putExtra("CURRENT_POSITION", position)
                }
                requireActivity().startActivity(intent)
            }

            // 需要传递控件 id加入歌单点击事件
            listAdapter?.addOnItemChildClickListener(R.id.tv_add_gedanlist) { adapter, view, position ->
                // toast("点了添加歌单")
                var song_item=adapter.items.get(position)
                // 将 MusicListBean 转换为 Song
                val song = Song().apply {
                    title = song_item.name ?: ""
                    artist = song_item.author ?: ""
                    cover = song_item.imageUrl ?: ""
                    uri=song_item.songUrl
                    duration = 0
                    songlistbean_id = 0
                }
                val repository = PlaylistRepository()
                var geDanList = repository.getAllPlaylists()
                    .filter { it.name != "本地音乐" }  // 过滤条件
                BottomPopupWithGeDanRecycler(requireActivity(), geDanList,song).show(mBinding.root)
            }

        }
    }


    override fun onResume() {
        super.onResume()
        mViewModel.loadPlaylists()
        //更改adapter中 第一个 isLocal为ture 的item中localCount 参数为本地数据库获取音乐的数量
         if (madapter!=null && madapter.items[0].isLocal){
            val localList = LitePal.findAll(AudioItemBean::class.java)
            madapter.items[0].localCount=localList.size
            madapter.notifyItemChanged(0)
        }
        checkMediaPermission()
    }

    override fun initObserve() {
      mViewModel.playlists.observe(this){
          madapter.submitList(it)
      }
    }


    override fun initListener() {
       mBinding.rvAddList.setOnClickListener {
           //新建歌单
           if (app_process=="0"){
               bottomCreateSongPop.show(it,77)
           }else{
               type_proces = "点击创建歌单"
               AdManager.loadVideo_nocache(
                   requireActivity(),
                   54,
                   this@SingerListFragment,
                   object : AdLoadListener {
                       override fun onAdLoadFailed(ad: IAdView?) {
                          bottomCreateSongPop.show(it,77)
                       }
                   })
           }

       }

      //控制列表选择管理
//        mBinding.tvNamager.setOnClickListener {
//            val shouldShow = !madapter.isSelectionVisible
//            madapter.toggleSelectionVisibility(shouldShow)
//            if (shouldShow){
//                mBinding.rvBottomDelete.visibility=View.VISIBLE
//                mBinding.tvNamager.text="完成"
//                selectMode=true
//            }else{
//                mBinding.rvBottomDelete.visibility=View.INVISIBLE
//                mBinding.tvNamager.text="歌单管理"
//                selectMode=false
//            }
//        }
      //adapter点击item事件
        madapter.setOnItemClickListener { adapter, view, position ->
            val item = adapter.items[position]
            if (selectMode){
                mViewModel.toggleItemSelection(item.id) // 切换选中状态
                adapter.items[position].isSelected=!adapter.items[position].isSelected
                madapter.notifyItemChanged(position)
            }else{
                if (item.isLocal){//如果是本地音乐
                    if (XXPermissions.isGranted(
                            requireContext(),
                            android.Manifest.permission.READ_MEDIA_AUDIO
                        )
                    ) {
                        var bundle = Bundle()
                        bundle.putString("category", "本地音乐")
                        launch(bundle, MusicListActivity::class.java)

                    } else {
                        request_Permission(
                            requireActivity(),
                            android.Manifest.permission.READ_MEDIA_AUDIO,
                            "音频权限",
                            "应用需要访问取您的存储权限，获取整个设备的音频文件资源用于播放器播放设备音乐"
                        )
                    }
                }else{
                    //点击进入歌单详情
                    var bundle = Bundle()
                    bundle.putString("cover", adapter.getItem(position)?.cover.toString())
                    bundle.putString("name", adapter.getItem(position)?.name.toString())
                    bundle.putLong("id", adapter.getItem(position)?.id!!)
                    launch(bundle, GeDanListActivity::class.java)
                }

            }


       }

       //移出歌单点击事件
        mBinding.rvBottomDelete.setOnClickListener {
            if (mViewModel.selectedItems.isNotEmpty()) {
              mViewModel.deleteSelectedPlaylists() // 执行删除
            } else {
               toast("请先选择要删除的歌单")
            }
        }


        mBinding.rvImportLocal.setOnClickListener {
            showMediaPermissionDialog()
        }
    }


    private fun checkMediaPermission() {
        if (XXPermissions.isGranted(
                requireContext(),
                android.Manifest.permission.READ_MEDIA_AUDIO
            )
        ) {
            loadAudioList()
        }
    }


    override fun loadAudioList() {
        showLoading("正在获取本地音乐")
        lifecycleScope.launch { // 使用 lifecycleScope 确保协程与 Activity 生命周期绑定
            try {
                // 调用 suspend 函数获取数据
                val audioList = mViewModel.getAudioInfoListSync()
                dismissLoading()
                // 更新 UI（）
                mBinding.rvImportLocal.visibility=View.GONE
                mBinding.rvGoLocal.visibility=View.VISIBLE
                mBinding.tvLocalAudioNum.text=audioList.size.toString()+"首"
                val songInfoList = mViewModel.convertToMusicListBeanList(audioList)
                listAdapter?.submitList(songInfoList)
            } catch (e: Exception) {
                // 处理错误（例如 Toast 提示）
                dismissLoading()
                toast("加载音频列表失败: ${e.message}")
            }
        }
    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {

    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        when(type_proces){
            "点击创建歌单"->{
                bottomCreateSongPop.show( mBinding.rvAddList,77)
            }
        }
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }


    val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let {
            // 将选中的图片传递给 BottomCreateSongPop
            bottomCreateSongPop?.setCoverUri(it)
        }
    }

    override fun onImageSelected() {
        getContent.launch("image/*")
    }

    override fun onCreateSuccess(playlistName: String, coverUri: String?) {
        mViewModel.addPlaylist(playlistName, coverUri ?: "")
        toast("创建成功")
    }

    override fun onDeleteGedan() {

    }

}